import { CartItemType } from "@/types/good";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { addCartAPI, deleteCartAPI, getCartListAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {
    // 购物车商品列表
    const cartList = ref<Array<CartItemType>>([]);

    const userStore = useUserStore();

    // 商品总数
    const totalCount = computed(() => cartList.value.reduce((pv, cv) => pv + cv.count, 0));

    // 商品总价
    const totalPrice = computed(() => cartList.value.reduce((pv, cv) => pv + cv.count * +cv.price, 0));

    // 添加商品至购物车
    const addCart = async (good: CartItemType) => {
        // 读取用户登录信息
        if (userStore.isLogin) {
            // 调用购物车接口
            const { skuId, count } = good;
            await addCartAPI({ skuId, count });
            getCartList();
        } else {
            const item = cartList.value.find(i => i.skuId === good.skuId);
            // 调整数量、新建条目
            if (item) {
                item.count += good.count;
            } else {
                cartList.value.push(good);
            }
        }
    };

    // 删除购物车单项
    const deleteCart = async (skuId: string) => {
        // 读取用户登录信息
        if (userStore.isLogin) {
            await deleteCartAPI([skuId]);
            getCartList();
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId);
        }
    };

    // 清空购物车
    const clearCart = () => {
        cartList.value = [];
    };

    // 获取最新购物车列表
    const getCartList = async () => {
        const { response } = getCartListAPI();
        cartList.value = (await response).data.result;
    };

    // 选中单项商品
    const selectSingle = (skuId: string, selected: boolean) => {
        const good = cartList.value.find(item => item.skuId === skuId);
        if (good) good.selected = selected;
    };

    // 选中全部商品
    const selectAll = (selected: boolean) => {
        cartList.value.forEach(item => item.selected = selected);
    };

    // 选中商品数量
    const selectedCount = computed(() => cartList.value.reduce((pv, cv) => pv + (cv.selected ? cv.count : 0), 0));

    // 选中商品总价
    const selectedPrice = computed(() => cartList.value.reduce((pv, cv) => pv + (cv.selected ? cv.count * +cv.price : 0), 0));

    return { cartList, totalCount, totalPrice, addCart, deleteCart, clearCart, getCartList, selectSingle, selectAll, selectedCount, selectedPrice };
}, { persist: true });